import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  Platform,
  TouchableOpacity,
  TextInput,
  ScrollView,
  Keyboard,
  DeviceEventEmitter,
} from 'react-native';

import PxToDp from '../../utils/PxToDp';
import SendFail from '../Public/SendFail';
import Footer from '../Public/Footer';
import Loading from '../Public/Loading';
import Base from '../../utils/Base';

import { fetchUserInfo, getVfCode, postLoginData, resetLogin } from '../../actions/loginActions';

const { width } = Base.window;

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
      verify: '',
      keyboardHeight: 0,
      isloading: false,
      marginBottom: 0,
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    // fetchUserInfo();
    dispatch(getVfCode((new Date()).getTime()));
  }
  async componentWillReceiveProps(nextProps) {
    const { dispatch } = this.props;
    if (nextProps.Login.errMessage) {
      this.setState({
        isloading: false,
      }, () => {
        DeviceEventEmitter.emit('showToast', nextProps.Login.errMessage, 800);
        dispatch(getVfCode((new Date()).getTime()));
        nextProps.Login.errMessage = '';
      });
    }
    if (nextProps.Login.isLogin) {
      dispatch(resetLogin());
      dispatch(fetchUserInfo());
      this.props.navigator.resetTo({
        title: '首页',
        name: '首页',
        component: Footer,
      });
    }
  }
  _getNewCode = (dispatch) => {
    dispatch(getVfCode((new Date()).getTime()));
  }
  _postLogin = (email, password, verify, dispatch) => {
    if (!email || !password || !verify) {
      return;
    }
    this.setState({ isloading: true });
    dispatch(postLoginData(email, password, verify));
  }

  componentWillUnmount() {
    this.keyboardDidHideListener.remove();
  }

  componentWillMount() {
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
  }

  _keyboardDidHide() {
    this.setState({
      keyboardHeight: 0,
    });
    if (Platform.OS === 'android') { // 软键盘消失，失去焦点
      this.textInput1.blur();
      this.textInput2.blur();
      this.textInput3.blur();
    }
  }

  _changeCode(text) {
    this.setState({ verify: text });
    if (Platform.OS === 'ios' && text.length === 4) { // 软键盘消失，失去焦点
      this.textInput1.blur();
      this.textInput2.blur();
      this.textInput3.blur();
    }
  }

  render() {
    const { code } = this.props.Login;
    const { dispatch } = this.props;
    return (
      <ScrollView style={{ marginTop: -this.state.keyboardHeight }}>
        <View style={{ flex: 1 }}>
          <View style={style.backgroundColor}>
            <Image style={{ height: PxToDp(217), width }} source={require('../../img/login.png')} />
          </View>
          <View style={style.position}>
            <View style={style.logo}>
              <Image style={style.logoimg} source={require('../../img/home/hLogo.png')} />
            </View>
            <Text style={style.slogan}>欢迎来到车易卖</Text>
          </View>
          <View style={style.verification}>
            <Image style={style.verificationimg} source={require('../../img/bj.png')} />
            <View style={[style.typeline, style.marginTop12]}>
              <Image style={style.typeimg} source={require('../../img/login_emil.png')} />
              <TextInput
                style={style.textinput}
                placeholder="邮箱号"
                onChangeText={text => this.setState({ email: text })}
                onFocus={() => this.setState({ keyboardHeight: 235 })}
                underlineColorAndroid="transparent"
                ref={(c) => { this.textInput1 = c; }}
              />
            </View>
            <View style={[style.typeline, style.marginTop18]}>
              <Image style={style.typeimg} source={require('../../img/login_key.png')} />
              <TextInput
                style={style.textinput}
                placeholder="密码"
                secureTextEntry
                onChangeText={text => this.setState({ password: text })}
                onFocus={() => this.setState({ keyboardHeight: 235 })}
                underlineColorAndroid="transparent"
                ref={(c) => { this.textInput2 = c; }}
              />
            </View>
            <View style={[style.typeline, style.vfCode]}>
              <Image style={style.typeimg} source={require('../../img/login_key.png')} />
              <TextInput
                style={style.textinput}
                placeholder="验证码"
                onChangeText={text => this._changeCode(text)}
                onFocus={() => this.setState({ keyboardHeight: 235 })}
                underlineColorAndroid="transparent"
                maxLength={4}
                ref={(c) => { this.textInput3 = c; }}
              />
              {
                (() => {
                  if (code) {
                    return (
                      <TouchableOpacity
                        activeOpacity={0.75}
                        onPress={() => this._getNewCode(dispatch)}
                      >
                        <Image style={style.vfIcon} source={{ uri: code }} />
                      </TouchableOpacity>
                    );
                  }
                })()
              }
            </View>
            <TouchableOpacity
              activeOpacity={0.75}
              style={style.btn}
              onPress={
                () => this._postLogin(
                    this.state.email,
                    this.state.password,
                    this.state.verify,
                    dispatch,
                  )
              }
            >
              <Text style={{ fontSize: 20, color: '#fff' }}>登陆</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={style.forgetBtn}
              activeOpacity={0.75} onPress={() => {
                this.props.navigator.push({
                  title: 'SendFail',
                  component: SendFail,
                });
              }}
            >
              <Text style={style.forget}>忘记密码？</Text>
            </TouchableOpacity>
          </View>
          {this.state.isloading ? <Loading /> : null}
        </View>
      </ScrollView>
    );
  }
}

const style = StyleSheet.create({
  position: {
    width,
    height: PxToDp(217),
    position: 'absolute',
    top: 0,
    alignItems: 'center',
  },
  textinput: {
    flex: 1,
    height: 42,
    paddingLeft: 20,
    marginTop: Platform.OS === 'ios' ? 10 : 0,
  },
  logo: {
    width: PxToDp(80),
    height: PxToDp(80),
    marginTop: Platform.OS === 'ios' ? 82 : 62,
  },
  typeimg: {
    width: 20,
    height: 20,
  },
  vfIcon: {
    width: PxToDp(90),
    height: PxToDp(24),
  },
  logoimg: {
    height: PxToDp(80),
    width: PxToDp(80),
  },
  verificationimg: {
    height: PxToDp(325),
    width: PxToDp(317),
    marginTop: 30,
  },
  slogan: {
    fontSize: 20,
    color: '#2D2E30',
    marginTop: 13,
  },
  verification: {
    alignItems: 'center',

  },
  typeline: {
    width: PxToDp(282),
    height: PxToDp(60),
    borderBottomWidth: 1,
    borderStyle: 'solid',
    borderColor: '#F0F0F0',
    flexDirection: 'row',
    alignItems: 'center',
  },
  marginTop12: {
    position: 'absolute',
    top: PxToDp(100),
  },
  marginTop18: {
    position: 'absolute',
    top: PxToDp(160),
  },
  vfCode: {
    position: 'absolute',
    top: PxToDp(220),
  },
  btn: {
    width: PxToDp(127),
    height: PxToDp(44),
    borderRadius: 22,
    backgroundColor: '#F65252',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: PxToDp(-50),
  },
  forgetBtn: {
    paddingBottom: PxToDp(20),
  },
  forget: {
    color: '#DC4437',
    marginTop: 20,
  },
});

